package com.xiaojian.pick.service.impl;

import com.alibaba.fastjson.JSON;
import com.xiaojian.pick.service.WxMessageService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author whycode
 * @title: WxMessageServiceImpl
 * @projectName campus-secondary-market-app---sys
 * @description: TODO
 * @date 2022/3/1216:38
 */

@Service
@Data
@Slf4j
public class WxMessageServiceImpl implements WxMessageService {
    @Value("${url}")
    private String url;
    @Value("${appid}")
    private String appid;
    @Value("${secret}")
    private String secret;

    @Resource
    private RestTemplate restTemplate;

    @Override
    public String token() {
        String path = "token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        ResponseEntity<Map> forEntity = restTemplate.getForEntity(url + path, Map.class);

        log.info("获取Token的结果为：{}", forEntity.getBody());

        if(forEntity.getStatusCodeValue() == 200){
            Map body = forEntity.getBody();
            return (String) body.get("access_token");
        }
        return null;
    }

    @Override
    public boolean send(Map<String, Object> msg) {
        String token = this.token();
        if(token == null){
            return false;
        }
        String path = "message/subscribe/send?access_token=" + token;
        log.info("s数据为\n {}", JSON.toJSONString(msg));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(msg, headers);
        ResponseEntity<Map> entity = restTemplate.postForEntity(url + path, request, Map.class);
        log.info("发送消息通知结果为：{}", entity.getBody());
        if(entity.getStatusCodeValue() == 200){
            Integer code = (Integer) entity.getBody().getOrDefault("errcode", -1);
            return code == 0;
        }
        return false;
    }
}
